package com.cty.knapsack;

/**
 * 动态规划算法解决背包问题
 */

public class knapsack {
    public static void main(String[] args) {
        int[] w = {1,4,3};//物品的重量
        int[] val = {1500,3000,2000};//物品的价格
        int i = val.length;
        int j = 4;//背包重量为4
        int[][] v = new int[i+1][j+1];
        int[][] path = new int[i+1][j+1];//放入物品额的方式
        //初始化背包
        for (int k = 0;k < v.length;k++) {
            v[k][0] = 0;
        }
        for (int k = 0;k < v[0].length;k++) {
            v[0][k] = 0;
        }
        for (int k = 1; k < v.length;k++) {
            for (int l = 1;l < v[i].length;l++) {
                if (w[k - 1] > l) {
                    v[k][l] = v[k-1][l];
                } else {
                    if (v[k - 1][l] <= (val[k - 1] + v[i - 1][l - w[k - 1]])) {
                        v[k][l] = val[k - 1] + v[i - 1][l - w[k - 1]];
                        path[k][l] = 1;
                    } else {
                        v[k][l] = v[k - 1][l];
                    }
                }
            }

        }
        //看一下初始情况
        for (int k = 0; k < v.length;k++) {
            for (int l = 0;l < v[0].length;l++) {
                System.out.print(v[k][l] + " ");
            }
            System.out.println();
        }

        int k = path.length - 1;
        int l = path[0].length - 1;
        while (k > 0 && l > 0) {
            if (path[k][l] == 1) {
                System.out.printf("第%d个物品放入背包\n",k);
                l -= w[i - 1];
            }
            k--;
        }
    }
}
